package com.bw.lib_image

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient

import java.io.File
import java.io.InputStream

/**
 * 自定义Glide内存和磁盘缓存大小
 */

@GlideModule
class CustomGlideModule:AppGlideModule() {

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        //1.修改内存缓存大小 设置缓存 默认内存大小是当前App内存大小的1/8
        val memorySize = MemorySizeCalculator.Builder(context).build().memoryCacheSize /6L
        builder.setMemoryCache(LruResourceCache(memorySize))

        //2.修改磁盘缓存大小 默认为250M
        builder.setDiskCache(InternalCacheDiskCacheFactory(context,"glide_disk_cache",300*1024*1024))

    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {

        //创建Builder对象 修改网络缓存大小
        val builder = OkHttpClient.Builder()

        //获取外部SD卡的缓存/存储目录
        val externalDir=Environment.getExternalStorageDirectory()
        var cacheDir=if (externalDir.exists()){
            //如果存在外部目录
            "${externalDir.absolutePath}/cacheImage"
        } else{
            //内部的SD卡的缓存目录
            "${context.externalCacheDir?.absolutePath}/internal_cache_img"

        }

        //创建缓存目录
        var cacheDirFile=File(cacheDir)
        if (!cacheDirFile.exists()){
            cacheDirFile=File(cacheDir)
        }

        //计算缓存大小
        var cacheSize= 50 * 1024 * 1024L
        externalDir.totalSpace?.let {
            cacheSize = it / 8L
        }
        var netWorkCache =Cache(cacheDirFile,cacheSize)


        //设置缓存目录
        builder.cache(netWorkCache)
        val newOkHttpClient = builder.build()//拿到一个客户端
        //替换网络缓存的客户端
        registry.replace(GlideUrl::class.java,InputStream::class.java,OkHttpUrlLoader.Factory(newOkHttpClient))
    }

}